clear all
set more off
set mem 10000000
set matsize 10000

***********************************************
** Randomiztaion test for NSS first stage DD **
***********************************************

** Set file paths
do "$path_code/paths.do"

**************************************************************
**************************************************************

** Estimate 10000 DDs with scrambled RGGVY 10th-Plan assignment

use "$panel/panel_dataset_dd_nss.dta", clear
set obs 10000
gen beta_extens_st_trends = .
gen beta_levels_st_trends = .
gen beta_logs_st_trends = .
tab treat_x_post if year==2010
tab vplan4 treat_x_post if year==2010, missing
count if vplan4<11 & year==2010
global n_treat = r(N)

gen row = _n
forvalues i = 1/10000 {
	
	qui gen temp = rnormal() if year==2010
	qui gsort temp
	qui gen temp_treat = 0
	qui replace temp_treat = 1 in 1/$n_treat
	qui gen temp_treat_x_post = temp_treat * (year==2010)
	
	qui reghdfe elec_q_yn temp_treat_x_post , a(year c.year#exp05_st_4ile c.year#exp05_ntl_10ile c.year#st_code stdt) //vce(cluster clustvar)
	qui replace beta_extens_st_trends = _b[temp_treat_x_post] if row==`i'
	
	qui reghdfe elec_quantity temp_treat_x_post , a(year c.year#exp05_st_4ile c.year#exp05_ntl_10ile c.year#st_code stdt) //vce(cluster clustvar)
	qui replace beta_levels_st_trends = _b[temp_treat_x_post] if row==`i'
	
	qui reghdfe log_elec_q temp_treat_x_post , a(year c.year#exp05_st_4ile c.year#exp05_ntl_10ile c.year#st_code stdt) //vce(cluster clustvar)
	qui replace beta_logs_st_trends = _b[temp_treat_x_post] if row==`i'

	qui drop temp*
	di `i'
		
}

keep beta_*
compress
save "$sens/nss_dd_randomization_test.dta", replace

